import { _decorator, Component, find, instantiate, Label, Node, Prefab, random, randomRange, randomRangeInt,CCString, BoxCollider2D, UITransform, director } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('GameManager')
export class GameManager extends Component {
	private static _instance: GameManager = new GameManager();

	@property([CCString])
	public workLabelList: string[] = []

	@property(Prefab)
	public workLabelPrefab: Prefab = null

	private _userdIndexSet: Set<number> = new Set()


	@property(Label)
	public timerLabel: Label = null;
  
	@property
	public timer: number = 0;

	private _curTime: number = 0;




	public static get instance(): GameManager {
		return this._instance
	}

	start() {
		console.log('gameManager-start')
		this._curTime = this.timer;
		this.timerLabel.string = this._curTime.toFixed(2);
		
		this.schedule(this.instantiateAndReplaceString, 0.5);
		
		
		
	}

	protected onLoad(): void {
		console.log('gameManager-start')
		if (GameManager._instance == null) {
			console.log('gameManager-start-null')
			GameManager._instance = new GameManager();
			
		} else {
			GameManager._instance = this;
			console.log('GameManager is already exist!')
			return;
			
		}
	}
	
	instantiateAndReplaceString() {
	
		let randomIndex: number = 0
		if (this._userdIndexSet.size === this.workLabelList.length) {
	
			this.unschedule(this.instantiateAndReplaceString)
			return
		}

		do {
			randomIndex = randomRangeInt(0, this.workLabelList.length)
		} while (this._userdIndexSet.has(randomIndex))

			

		this._userdIndexSet.add(randomIndex)
		const workLabelNode = instantiate(this.workLabelPrefab)
		this.scheduleOnce(() => {
			workLabelNode.getComponent(BoxCollider2D).size = workLabelNode.getComponent(UITransform).contentSize
			workLabelNode.getComponent(BoxCollider2D).apply();
		}, 0)
	
		workLabelNode.getComponent(Label).string = this.workLabelList[randomIndex]
		workLabelNode.parent = find('Canvas/WorkLabelList')
		workLabelNode.setPosition(randomRange(-320, 320), 670)
		
	}


	update(deltaTime: number) {
		this._curTime -= deltaTime;
		if (this._curTime <= 0) {
			this._curTime = 0;
			this.timerLabel.string = '0.00';
			
		} else {
			this.timerLabel.string = this._curTime.toFixed(2);
		}
	}


	reloadGame() {
	
		director.loadScene(director.getScene().name);
		
	}
	
}


